package com.weijianhuawen.wjblog.web.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description:  Markdown 数字统计
 * @date: 2024-11-05 23:26
 */
public class MarkdownStatsUtil {
    // 每分钟阅读字数
    private static final Integer WORDS_READ_PRE_MINUTE = 300;

    // 计算markdown 字数 按词计算
    public static int calculateWordCount(String markdown) {
        // 将markdown 中连续的空白字符（包括空格，制表符，换行符等）替换成一个空格
        String cleanText = markdown.replaceAll("\\s+", " ");
        // 使用正则表达式匹配中文
        Pattern chinesePattern = Pattern.compile("[\\u4e00-\\u9fa5]");
        Matcher chineseMatcher = chinesePattern.matcher(cleanText);

        // 计算中文字数
        Integer chineseCount = 0;
        while (chineseMatcher.find()) {
            chineseCount++;
        }
        // 去除中文
        String textWithoutChinese = cleanText.replaceAll("[\\u4e00-\\u9fa5]", "");
        if (StringUtils.isBlank(textWithoutChinese)) return chineseCount;
        // 使用空格分割文本为单词
        String[] words = textWithoutChinese.trim().split("\\s+");
        return chineseCount + words.length;
    }

    // 计算阅读时长
    public static String calculateReadingTime(Integer wordCount) {
        // 判断字数是否大于一分钟所阅读的字数
        if (wordCount >= WORDS_READ_PRE_MINUTE) {
            // 计算花费分钟数
            Integer minutes = wordCount / WORDS_READ_PRE_MINUTE;
            return "约" + minutes + "分钟";
        }
        // 如果字数小于一分钟阅读字数，按照秒进行计算
        Integer seconds = (wordCount % WORDS_READ_PRE_MINUTE) * 60 / WORDS_READ_PRE_MINUTE;
        if (seconds == 0) seconds = 1;
        return "约" + seconds + "秒";
    }
}
